﻿/*--------------------------------------------------
 Creater：Junxuan.Su
 Time：2013-12-12 14:35:33
 Remark : Json
--------------------------------------------------*/

using System;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;

namespace HXDNB.Infrastructure.Helper
{
    public class Json
    {
        /// <summary>
        /// 将对象转换为Json字符串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>Json字符串</returns>
        public static string Convert(object obj)
        {
            try
            {
                var serializer = new JavaScriptSerializer();
                return serializer.Serialize(obj);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 将对象保存为Json文件
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="obj">对象</param>
        /// <returns>是否成功</returns>
        public static bool Save(string path, object obj)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(path))
                    return false;

                if (!Directory.Exists(Path.GetDirectoryName(path)))
                    Directory.CreateDirectory(Path.GetDirectoryName(path));

                File.WriteAllText(path, Convert(obj), Encoding.UTF8);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error("Json.Save", ex.Message + ex.StackTrace);
                return false;
            }
        }
    }
}
